local meta = FindMetaTable( "Player" );

function meta:HandleUID( b )

	local query = "SELECT * FROM `users` WHERE `SteamID` = '" .. self:SteamID() .. "'";
	local user = sql.Query( query )[1]
	
	if( b ) then
	
		self:SetPlayerUID( user["uid"] );
	
		if( string.find( user["HasToolTrust"], "advanced" ) ) then
			self:Give( "gmod_tool" );
			self:GetTable().AdvancedTT = true;
		end

		if( string.find( user["CanDupe"], "yes" ) ) then
			self:GetTable().CanUseDuplicator = true;
		end	
		
	else	

		self:SetPlayerUID( user["uid"] );
		self:SetNWString( "Flags", user["PlayerFlags"] )
		
	end	
	
	
end

function meta:SaveContainers()

	local cmd = "UPDATE `characters` SET `containers` = '";
	
	for n = 1, TS.MaxInventories do
	
		local cont = self:GetTable().Inventories[n].Name or ""
		cmd = cmd .. cont .. ";"
		
	end	
	
	cmd = cmd .. "' WHERE SteamID = '" .. self:SteamID() .. "' AND id = '" .. self:GetField( "charid" ) .. "';";
	
	sql.Query( cmd );
	
end	

function meta:SaveItems()
	
	local cmd = "UPDATE `characters` SET `Items` = '";
	
	for i, v in pairs( self:GetTable().InventoryGrid ) do
	
		for x, c in pairs( v ) do
		
			for y, u in pairs( c ) do
				
				if( self:GetTable().InventoryGrid[i][x][y].ItemData ) then
				
				local item = self:GetTable().InventoryGrid[i][x][y].ItemData.ID
				
				cmd = cmd .. item .. ";"
				
				end
				
			end
			
		end

	end

	cmd = cmd .. "' WHERE SteamID = '" .. self:SteamID() .. "' AND id = '" .. self:GetField( "charid" ) .. "';";
	
	sql.Query( cmd );
	
end	

function meta:SaveCharacter()

	local cmd = "INSERT INTO `characters` ";
	
	local fields = { };
	fields["RPName"] = self:GetNWString( "RPName" );
	fields["Model"] = self:GetField( "CitizenModel" );
	fields["SteamID"] = self:SteamID();
	fields["Tokens"] = self:GetPlayerMoney();
	fields["Title"] = self:GetPlayerTitle();
	fields["SecondTitle"] = self:GetPlayerSecondTitle();
	fields["ClassMark"] = self:GetPlayerClassMark();
	fields["Age"] = self:GetPlayerAge();
	fields["Faction"] = self:GetPlayerFaction();

	cmd = cmd .. "( ";

	local comma = false;

	for k, v in pairs( fields ) do
	
		if( comma ) then
			cmd = cmd .. ", ";
		end
	
		cmd = cmd .. k;
		comma = true;
	
	end
	
	cmd = cmd .. ") VALUES ( ";
	
	local comma = false;
	
	for k, v in pairs( fields ) do
	
		if( comma ) then
			cmd = cmd .. ", ";
		end
	
		cmd = cmd .. "'" .. v .. "'";
		comma = true;
	
	end	

	cmd = cmd .. "); ";

	sql.Query( cmd );
	
	local id = sql.Query( "SELECT id FROM `characters` WHERE SteamID = '" .. self:SteamID() .. "' AND RPName = '" .. self:GetRPName() .. "'" )[1]["id"];
 	id = tonumber( id );
 	
 	self:SetField( "charid", id );
	
	timer.Simple( 5, function()
	
		self:SaveContainers()
		self:SaveItems()
		
	end )	
	
 	
end

function meta:UpdateCharacter()

	local cmd = "UPDATE `characters` SET ";
	
	local fields = { }
	fields["Tokens"] = self:GetField( "Money" )
	fields["ClassMark"] = self:GetField( "ClassMark" )
	fields["CombineFlags"] = self:GetField( "CombineFlags" )
	fields["Title"] = self:GetPlayerTitle();
	fields["SecondTitle"] = self:GetPlayerSecondTitle();
	fields["PlayerFlags"] = self:GetField( "PlayerFlags" )

	cmd = cmd .. "( ";
	local comma = false;

	for k, v in pairs( fields ) do
	
		if( comma ) then
			cmd = cmd .. ", ";
		end
	
		cmd = cmd .. k .. " = '" .. v .. "'";
		comma = true;
		
	end
	
	cmd = cmd .. " WHERE SteamID = '" .. self:SteamID() .. "' AND id = '" .. self:GetField( "charid" ) .. "';";
	sql.Query( cmd );

 	self:SaveItems()
	self:SaveContainers()
	
end

	
function meta:GetNumCharacters( steamid )

	local list = sql.Query( "SELECT * FROM characters WHERE SteamID = '" .. steamid .. "'" )
		
	if( !list ) then
		return 0
	end	

	return #list
	
end	

function meta:GetCharacterList()

	local cmd = "SELECT id FROM `characters` WHERE SteamID = '" .. self:SteamID() .. "'";

	return doQuery( cmd );

end

function meta:HasCharacter( name )

	local result = sql.Query( "SELECT id FROM `characters` WHERE SteamID = '" .. self:SteamID() .. "' AND RPName = '" .. name .. "'" )
	
	if( !result ) then 
		return false 
	end
	
	return true

end

function meta:SaveExists( nick )

	local query = "SELECT `id` FROM `characters` WHERE `id` = '" .. self:GetField( "charid" ) .. "' AND `RPName` = '" .. nick .. "'";
	
	if( query ) then
	
		return true
		
	end	

end

function meta:SaveData( name, val )

	local cmd = "UPDATE `characters` SET " .. name .. " = '" .. val .. "' WHERE SteamID = '" .. self:SteamID() .. "' AND id = '" .. self:GetField( "charid" ) .. "';";
	
	sql.Query( cmd );	

end		
--	self:SetPlayerFaction( character["Faction"] );

Clothes = {

	{ "Pockets", "clothes_citizen" },
	{ "Metrocop Jacket", "clothes_metrocop" },
	{ "Rebel Vest", "clothes_rebel" },
	{ "Rebel Medic Vest", "clothes_rebelmedic" },
	{ "Vortigaunt Pouch", "clothes_vortpouch" },
	{ "Formal Suit", "clothes_cajacket" },
	{ "CWU Clothing", "clothes_cwu" },
	{ "High-Quality Citizens Jacket", "clothes_jacket" },
	{ "Overwatch Uniform", "clothes_overwatchsuit.lua" }
	
}	

function meta:LoadCharacter( id )

	local query = "SELECT * FROM `characters` WHERE id = '" .. id .. "'";

	local character = sql.Query( query )[1];
	
	self:SetNWString( "title", tostring( character["Title"] ) )
	self:SetNWString( "secondtitle", tostring( character["SecondTitle"] ) )
	self:SetField( "CitizenModel", character["Model"] )
	self:GetTable().CCModel = self:GetField( "CitizenModel" )
	self:SetNWFloat( "CID", character["CID"] )
	--self:SetPlayerCID( character["CID"] );
	
	self:SetPlayerAge( character["Age"] );
	self:SetModel( character["Model"] )
	
	self:SetField( "combineflags", tostring( character["CombineFlags"] ) )
	self:SetField( "playerflags", tostring( character["PlayerFlags"] ) )
	self:SetPlayerClassMark( character["ClassMark"] ) 
	self:SetPlayerMoney( tonumber( character["Tokens"] ) )
	self:SetPlayerLoans( tonumber( character["Loan"] ) )
	self:SetPlayerClassStatus( tonumber( character["ClassStatus"] ) )
	
	self:SetPlayerFaction( character["Faction"] );
	self:SetPlayerCharacterFlags( character["CharFlags"] );
		
	local containers = string.Explode( ";", character["containers"] );
	
	for k, v in pairs( containers ) do	
	
		for n, m in pairs( Clothes ) do
		
			if( v == m[1] ) then
			
				self:WearItem( m[2] )
				
			end

		end	
		
	end
		
	local items = string.Explode( ";", character["Items"] );	
		
	for k, v in pairs( items ) do
	
	    if( v and v ~= "" ) then		
		
			if( self:HasItem( v ) ) then return end
			
			if( self:IsCitizen() ) then
			
				self:GiveAnyInventoryItem( v );
				if( string.find( v, "ts2_" ) ) then
					self:Give( v );
				end
				
			else
			
				self:GiveAnyInventoryItem( v );
				if( string.find( v, "ts2_" ) ) then
					self:Give( v );
				end
				
			end
			
		end
		
	end
	
	self:Spawn()
		
	self:SetNWString( "RPName", character["RPName"] )
	self:SetField( "charid", id );
	
	character = nil
	
end	
	
	